package cc.sheji.Service;


import cc.sheji.domain.*;
import cc.sheji.reposity.CategoryRepository;
import cc.sheji.util.QueryHelp;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
public class CategoryService {

    @Autowired
    CategoryRepository categoryRepository;

    public Category create(Category entity) {
        entity.setId(null);
        entity = categoryRepository.save(entity);
        return entity;
    }

    public Category get(@PathVariable("id") Long id) {
        Category entity = categoryRepository.findById(id).get();
        return entity;
    }

    public List<Category> list(CategoryQueryCriteria criteria, Pageable pageable) {
        Sort order = Sort.by(Sort.Direction.DESC, "weight");
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);
        Page<Category> page = categoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return page.getContent();
    }


    public Category update(Category job) {
        Category entity = categoryRepository.findById(job.getId()).get();
        entity.setImage(job.getImage());
        entity.setType(job.getType());
        entity.setEnglishName(job.getEnglishName());
        entity.setName(job.getName());
        entity.setWeight(job.getWeight());
        entity.setParentId(job.getParentId());
        return categoryRepository.save(entity);
    }

    public boolean delete(long id) {
        Category ad = categoryRepository.findById(id).get();
        ad.setDeleted(1);
        categoryRepository.save(ad);
        return true;
    }

    public Object getAll(CategoryQueryCriteria criteria) {

        List<Category> all = categoryRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<Category> returnList = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            Category item = all.get(i);
            if (item.getParentId() == null || item.getParentId() == 0)
                returnList.add(item);
        }
        for (int i = 0; i < all.size(); i++) {
            Category item = all.get(i);
            for (int k = 0; k < returnList.size(); k++) {

                Category category = returnList.get(k);
                Long id = category.getId();
                Long parentId = item.getParentId();
                List<Category> child = category.getChild();
                if (child == null)
                    child = new ArrayList<>();
                if (id .equals(parentId) ) {
                    child.add(item);
                }
                category.setChild(child);
            }
        }

        for (int i = 0; i < all.size(); i++) {
            Category item = all.get(i);
            for (int k = 0; k < returnList.size(); k++) {
                Category category1 = returnList.get(k);

                for (int m = 0; m < category1.getChild().size(); m++) {
                    Category category2 = category1.getChild().get(m);
                    Long id = category2.getId();
                    Long parentId = item.getParentId();
                    List<Category> child2 = category2.getChild();
//                    System.out.println("category2:"+category2);
//                    System.out.println("item:"+item);
                    System.out.println("id:"+id);
                    System.out.println("parentId:"+parentId);

                    if (child2 == null)
                        child2 = new ArrayList<>();
                    if (id .equals(parentId) ) {
                        System.out.println("equal id");
                        child2.add(item);
                    }
                    category2.setChild(child2);
                }
            }
        }
        return returnList;
    }


    public boolean importExcel(final MultipartFile file, Long id) throws IOException {

        System.out.println(id);
        new Thread(new Runnable() {
            @Override
            public void run() {

                List<Category> all = categoryRepository.findAll(null);
                List<Category> returnList = new ArrayList<>();
                ArrayList<Long> ids=new ArrayList<>();
                for (int i = 0; i < all.size(); i++) {
                    Category item = all.get(i);
                    if (item.getParentId() == null || item.getParentId() == id){
                        returnList.add(item);
                        ids.add(item.getId());
                    }
                }
                for (int i = 0; i < all.size(); i++) {
                    Category item = all.get(i);
                    for (int k = 0; k < returnList.size(); k++) {
                        Category category = returnList.get(k);
                        Long id = category.getId();
                        Long parentId = item.getParentId();
                        List<Category> child = category.getChild();
                        if (child == null)
                            child = new ArrayList<>();
                        if (id .equals(parentId) ) {
                            child.add(item);
                            ids.add(item.getId());
                        }
                        category.setChild(child);
                    }
                }
                categoryRepository.deleteAllById(ids);
                //io流给ExcelReader
                ExcelReader excelReader = null;
                try {
                    excelReader = ExcelUtil.getReader(file.getInputStream());
                    List<Sheet> sheets = excelReader.getSheets();
                    for (int i = 0; i < sheets.size(); i++) {

                        Sheet sheet = sheets.get(i);
                        String name = sheet.getSheetName();
                        System.out.println(name);
                        Category category = new Category();
                        category.setName(name);
                        category.setEnglishName("");
                        category.setType(2);
                        category.setParentId(id);
                        category = create(category);
                        excelReader.setSheet(sheet);
                        List<List<Object>> list = excelReader.read(1);
                        for (List<Object> row : list) {
                            System.out.println(row.toString());
                            Category category1 = new Category();
                            category1.setName(row.get(0).toString());
                            category1.setEnglishName(row.get(1).toString());
                            category1.setType(Integer.parseInt(row.get(2).toString()));
                            category1.setParentId(category.getId());
                            create(category1);
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


            }
        }).start();

        return true;

    }
}
